//
//  WJGroupTableViewController.m
//  JerryIos
//
//  Created by jerrywang on 2018/2/4.
//  Copyright © 2018年 王军. All rights reserved.
//

#import "WJGroupTableController.h"
#import "WJCarBrand.h"
#import "WJCar.h"

@interface WJGroupTableController ()

@property (nonatomic, strong) NSArray *carBrandArray;

@end

@implementation WJGroupTableController

- (NSArray *)carBrandArray {
    if (_carBrandArray == nil) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"car.plist" ofType:nil];
        NSArray *dicArray = [NSArray arrayWithContentsOfFile:path];
        
        NSMutableArray *groupArray = [NSMutableArray array];
        for (NSDictionary *dic in dicArray) {
            WJCarBrand *carBrand = [WJCarBrand carBrandWithDict:dic];
            [groupArray addObject:carBrand];
        }
        _carBrandArray = groupArray;
    }
    return _carBrandArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.carBrandArray.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    WJCarBrand *carBrand = self.carBrandArray[section];
    return carBrand.title;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return [self.carBrandArray valueForKeyPath:@"title"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    WJCarBrand *carBrand = self.carBrandArray[section];
    return carBrand.carArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:cellId];
    }
    WJCarBrand *carBrand = self.carBrandArray[indexPath.section];
    WJCar *car = carBrand.carArray[indexPath.row];
    cell.imageView.image = [UIImage imageNamed:car.icon];
    cell.textLabel.text = car.name;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
